package edu.suda.xsap.service.impl;
import edu.suda.xsap.dto.EmployeeDto;
import edu.suda.xsap.dto.convert.EmployeeConvert;
import edu.suda.xsap.entity.Employee;
import edu.suda.xsap.entity.vo.TeacherVo;
import edu.suda.xsap.mapper.EmployeeMapper;
import edu.suda.xsap.mapper.TeacherVoMapper;
import edu.suda.xsap.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service

public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private EmployeeConvert employeeConvert;
    @Autowired
    private TeacherVoMapper teacherVoMapper;
    @Override
    public void delete(Integer id) {
        employeeMapper.delete(id);
    }

    @Override
    public List<EmployeeDto> findAll() {
        return employeeConvert.toDtoList(employeeMapper.findAll());
    }

    @Override
    public EmployeeDto findById(Integer id) {
        return employeeConvert.toDto(employeeMapper.findById(id));
    }



    @Override
    public void save(Employee employee) {
        employee.setCreateTime(LocalDateTime.now());

        if (employeeMapper.findByPhone1(employee.getPhone())!=null){
            if (employeeMapper.findIsDelete(employee.getPhone())==1){
                employeeMapper.changeIsDelete(employee.getPhone());
                employee.setId(employeeMapper.findIdByPhone(employee.getPhone()));
                employeeMapper.update(employee);
                return;
            }
            throw new RuntimeException("该手机号已存在");
        }
        employeeMapper.save(employee);
    }

    @Override
    public void update(Employee employee) {
        try {employeeMapper.update(employee);}
        catch (Exception e){
            throw new RuntimeException("更新失败");
        }


    }

    @Override
    public List<EmployeeDto> findByLimit(Integer limit, Integer offset) {
        return employeeConvert.toDtoList(employeeMapper.findByLimit(limit,offset));
    }

    @Override
    public Integer findCount() {
        return employeeMapper.findCount();
    }

    @Override
    public List<TeacherVo> record(Integer id) {
        return teacherVoMapper.findByEmployeeId(id);
    }

    @Override
    public String findByPhone(String phone) {
        return employeeMapper.findByPhone(phone);
    }
}
